﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Xml;
using System.Reflection;
using GamePlugin.IO;
using UnityEngine.IO;

namespace GamePlugin.Logics
{
    public class PluginObject : DependencyObject
    {
        private XmlNode _XmlNode;

        public virtual void ReadXml(XmlNode root)
        {
            // record xml node
            this._XmlNode = root;

            Dictionary<string, XmlNode> children = new Dictionary<string, XmlNode>();
            for (int i = 0; i < root.ChildNodes.Count; i++)
                children.Add(root.ChildNodes[i].Name, root.ChildNodes[i]);

            Serializer serializer = new Serializer();

            PropertyInfo[] properties =
                this.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
            for (int i = 0; i < properties.Length; i++)
            {
                PropertyInfo info = properties[i];
                if (info.CanWrite == false ||
                    info.CanRead == false)
                    continue;
                if (info.GetCustomAttributes(typeof(EditableAttribute), false).Length > 0)
                {
                    if (children.ContainsKey(info.Name) == true)
                    {
                        object value = serializer.Deserialize(info.Name, children[info.Name], info.PropertyType);
                        if (value != null)
                            info.SetValue(this, value, null);
                    }
                }
            }
        }

        public virtual void WriteXml(XmlWriter writer)
        {
            Serializer serializer = new Serializer();

            PropertyInfo[] properties =
                this.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
            for (int i = 0; i < properties.Length; i++)
            {
                PropertyInfo info = properties[i];
                if (info.CanWrite == false ||
                    info.CanRead == false)
                    continue;
                if (info.GetCustomAttributes(typeof(EditableAttribute), false).Length > 0)
                {
                    serializer.Serialize(info.Name, info.GetValue(this, null), writer, info.PropertyType);
                }
            }
        }

    }
}
